import * as $apis from '@/apis/index.js';
// #ifdef H5
import wechat from '@/libs/wechat.js';
// #endif

function pay(type = 'wx', orderType = 'orderPay', orderData = {}) {
	if (type == 'wx') {
		let obj = {
			order_sn: orderData.order_sn || '',
			// #ifdef H5
			pay_type: wechat.isWeixin() ? "official" : 'h5',
			// #endif
			// #ifdef MP-WEIXIN
			pay_type: "mini_program",
			// #endif
			// #ifdef APP-PLUS
			pay_type: "app",
			// #endif
		}
		if (orderType == 'rechargeMoney') {
			obj = {
				select_id: orderData.select_id || 0,
				price: orderData.price || '',
				// #ifdef H5
				type: wechat.isWeixin() ? "official" : 'h5',
				// #endif
				// #ifdef MP-WEIXIN
				type: "mini_program",
				// #endif
				// #ifdef APP-PLUS
				type: "app",
				// #endif
			}
		}
		$apis[orderType](obj).then((res) => {
			// #ifdef H5
			wcPayH5(res)
			// #endif
			// #ifdef MP-WEIXIN
			wcPayMP(res)
			// #endif
			// #ifdef APP-PLUS
			wcPayAPP(res)
			// #endif
		})
	}
	let wcPayMP = function(payData) {
		uni.requestPayment({
			provider: 'wxpay',
			timeStamp: payData.timestamp,
			nonceStr: payData.nonceStr,
			package: payData.package,
			signType: payData.signType,
			paySign: payData.paySign,
			success: function(res) {
				uni.showToast({
					icon: "success",
					title: "支付成功"
				})
				requestSubscribeMessage(['delivery_express', 'delivery_send', 'delivery_success'],
					function() {
						paySuccess()
					});
			},
			fail: function() {
				payFail()
			},
			complete: function(res) {
				if (res.errMsg == 'requestPayment:cancel') {
					payCancle()
				}
			}
		});
	};
	let wcPayAPP = function(payData) {
		let orderInfo = payData;
		uni.requestPayment({
			"provider": 'wxpay',
			"orderInfo": orderInfo,
			success: function(res) {
				paySuccess
			},
			fail: function(err) {
				payFail()
			},
			complete: function(res) {
				if (res.errMsg == 'requestPayment:cancel') {
					payCancle()
				}
			}
		});
	};
	let wcPayH5 = function(payData) {
		let obj = {
			data: payData,
			success: function() {
				paySuccess()
			},
			fail: function() {
				payFail()
			}
		}
		wechat.wxpay(obj)
	};
	let paySuccess = function() {
		orderData.success ? orderData.success() : '';
		setTimeout(() => {
			uni.showToast({
				icon: "success",
				title: "支付成功"
			})
		}, 1000)
	};
	let payFail = function() {
		orderData.fail ? orderData.fail() : '';
		uni.showToast({
			title: "支付失败",
			icon: "none"
		})
	}
	let payCancle = function() {
		orderData.payCancle ? orderData.payCancle() : '';
		uni.showToast({
			title: "取消支付",
			icon: "none"
		})
	}
}
export default pay
